import { ReactElement, useRef, useEffect, useState } from 'react'
import { Modal, Form, FormInstance, Select, message, Input } from 'antd'
import { caseInputRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import Text from '@components/text'
import Dictionary, { DictionaryItem } from '@js/dictionary'

const { Item } = Form
const { TextArea } = Input
const { Option } = Select

async function submitHandle (data: { [k: string]: any }, hide: () => void, refreshData: () => void): Promise<void> {
  delete data.serieno
  const h = message.loading('提交中', 120)
  const [e] = await awaitWrap(caseInputRequest(data))
  h()
  if (e === null) {
    message.success('提交成功').then(null, null)
    refreshData()
    hide()
  }
}

interface Props {
  visible: boolean
  hide: () => void
  data: { [k: string]: any } | null
  refreshData: () => void
}

function Main ({ visible, hide, data, refreshData }: Props): ReactElement {
  const formRef = useRef<FormInstance>(null)
  const [options, setOptions] = useState<DictionaryItem[]>([])
  const [typeMap, setTypeMap] = useState<{[k: string]: string}>({})
  useEffect(() => {
    const c = formRef.current
    if (c !== null && data !== null) {
      c.setFieldsValue(data)
    }
  }, [data, formRef])
  useEffect(() => {
    const c = formRef.current
    if (!visible && c !== null) {
      c.resetFields()
    }
  }, [visible, formRef])
  useEffect(() => {
    const d = new Dictionary()
    d.init('系列案标签,系列案类型')
      .then(() => {
        setOptions(d.getList('系列案标签'))
        setTypeMap(d.getMap('系列案类型'))
      })
      .catch(e => console.error(e))
  }, [])
  return (
    <Modal title='编辑系列案' visible={visible} onCancel={hide} onOk={() => formRef.current?.submit()} maskClosable={false} destroyOnClose>
      <Form ref={formRef} labelCol={{ flex: '88px' }} initialValues={data === null ? {} : data} onFinish={async d => await submitHandle(d, hide, refreshData)}>
        <Item name='id' noStyle><span /></Item>
        <Item name='serieno' label='系列号'>
          <Text />
        </Item>
        <Item name='type' label='系列案类型'>
          <Text format={v => typeof v === 'string' && typeof typeMap[v] === 'string' ? typeMap[v] : ''} />
        </Item>
        <Item name='tag' label='标签' rules={[{ required: true, message: '标签不能为空' }]}>
          <Select placeholder='请选择'>
            {options.map((li, i) => <Option key={i} value={li.value}>{li.title}</Option>)}
          </Select>
        </Item>
        <Item name='remark' label='备注'>
          <TextArea autoSize={{ minRows: 3 }} />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
